package tornadoj.web;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tornadoj.points.IScheduler;
import tornadoj.points.IServerStartup;
import tornadoj.util.Utils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Web 服务器加载
 * Created by tinyms on 13-12-18.
 */
@WebServlet(name = "StartupServlet", loadOnStartup = 1, urlPatterns = "/StartupServlet")
public class StartupServlet extends HttpServlet {
    private static Logger Log = LoggerFactory.getLogger(StartupServlet.class);
    private final static SchedulerFactory sf = new StdSchedulerFactory();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        TornadoJConfiguration.loadProperties();
        Registry.self().clear();

        SimpleCache.registerCacheForever(SimpleCache.CACHE_NAME_TEMPLATE);
        SimpleCache.registerCacheForever(SimpleCache.CACHE_NAME_MASTER_TEMPLATE);

        String path = config.getServletContext().getRealPath("/");
        if (!StringUtils.endsWith(path, File.separator)) {
            path = path + File.separator;
        }

        Log.info(path);

        TornadoJConfiguration.SiteAbsPath = path;
        TornadoJConfiguration.TemplatePath = path + "WEB-INF/templates/";

        String layoutCachePath = String.format("%s%s", TornadoJConfiguration.TemplatePath, "cache");
        Utils.mkdirs(layoutCachePath);

        ClassLoaderUtil.regObjectsToPool();
        ClassLoaderUtil.loadAnnotations("tornadoj");

        for (String packageName : TornadoJConfiguration.PluginPackagePrefix) {
            ClassLoaderUtil.loadAnnotations(packageName);
        }

        for (String packageName : TornadoJConfiguration.PluginPackagePrefix) {
            ClassLoaderUtil.loadPlugins(packageName);
        }

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        try {
            cfg.setDirectoryForTemplateLoading(new File(TornadoJConfiguration.TemplatePath));
            cfg.setDefaultEncoding("utf-8");
            cfg.setDateFormat(TornadoJConfiguration.DateFormat);
            cfg.setDateTimeFormat(TornadoJConfiguration.DateTimeFormat);
            cfg.setSharedVariable("SiteUrl", TornadoJConfiguration.SiteUrl);
            cfg.setSharedVariable("Version", TornadoJConfiguration.Ver);
        } catch (IOException e) {
            Log.error(e.getLocalizedMessage(), e);
            e.printStackTrace();
        } catch (TemplateModelException e) {
            Log.error(e.getLocalizedMessage(), e);
        }

        ClassLoaderUtil.printInfo();

        // Web服务器启动Hook
        List<IServerStartup> iServerStartups = ClassLoaderUtil.getPlugin(IServerStartup.class);
        for (IServerStartup iServerStartup : iServerStartups) {
            iServerStartup.doInStartup(this);
        }

        try {
            // 定时器Hook
            Scheduler sched = sf.getScheduler();
            List<IScheduler> iSchedulers = ClassLoaderUtil.getPlugin(IScheduler.class);
            for (IScheduler iScheduler : iSchedulers) {
                iScheduler.doInScheduler(sched);
            }
            sched.start();
        } catch (SchedulerException e) {
            Log.error(e.getLocalizedMessage());
        }
    }



    @Override
    public void destroy() {
        SimpleCache.getCacheManager().shutdown();
        super.destroy();
    }
}
